package com.openatc.agent.service.impl;

import com.openatc.agent.service.GenericMsgStrategy;
import com.openatc.agent.utils.RedisTemplateUtil;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.openatc.core.common.IErrorEnumImplInner.E_110;

/**
 * @Classname LoginRequest
 * @Description 处理Login请求
 * @Date 2022/7/19 17:06
 * @Created by panleilei
 */
@Service(value = "login")
public class LoginRequest extends GenericMsgStrategy {
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;
    private String keyType = "response:login:";
    private String dataSource = "Cache";

    /**
     * 信号机成功应答login请求
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successGetProcess(MessageData requestData, RESTRet responseData) {
        MessageData res = (MessageData) responseData.getData();
        // 更新login的缓存
        updateLoginCache(requestData.getAgentid(),res);
        return super.successGetProcess(requestData, responseData);
    }

    /**
     * 信号机应答login请求失败
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet failureGetProcess(MessageData requestData, RESTRet responseData) {
        InnerError innerError = (InnerError) responseData.getData();
        String agentid = requestData.getAgentid();
        // 上次login的请求未结束/login请求应答超时
        if (innerError.getErrorCode().equals(E_110.getErrorCode()) ) {
            return redisTemplateUtil.getCacheData(requestData);
        } else {
            // 其他错误，清空缓存，应答错误
            clearLoginCache(agentid);
        }

        return super.failureGetProcess(requestData, responseData);
    }

    /**
     * login应答成功，更新login的缓存状态
     * @param agentid
     * @param res
     */
    private void updateLoginCache(String agentid, MessageData res) {
        String key = keyType + agentid;
        res.setCreatetime(DateUtil.date2esstr(new Date()));
        redisTemplateUtil.setValue(key,gson.toJson(res));
    }

    /**
     * 从redis中获取缓存的数据
     * @param agentid
     * @return
     */
    private String getLoginCache(String agentid) {
        String key = "response:login:" + agentid;
        return redisTemplateUtil.getValue(key);
    }

    /**
     * 清空缓存数据
     * @param agentid
     */
    private void clearLoginCache(String agentid) {
        String key = "response:login:" + agentid;
        redisTemplateUtil.delete(key);
    }
}
